<!-- eslint-disable @typescript-eslint/no-unused-vars -->
<template>
  <div class="h-full">
    <n-space vertical>
      <n-card class="shadow-sm rounded-4px h-68px">
        <n-form class="w-full" size="small" inline>
          <n-form-item label="日期:" label-placement="left">
            <n-date-picker
              v-model:value="range"
              type="datetimerange"
              clearable
              :default-time="['00:00:00', '00:00:00']"
            />
          </n-form-item>
          <n-form-item label="型号:" label-placement="left">
            <n-input v-model:value="selectedModelType" style="width: 100px" type="text" placeholder="" />
          </n-form-item>
          <n-form-item label="车间:" label-placement="left" style="width: 200px">
            <n-select
              v-model:value="selectedAreas"
              clearable
              multiple
              label-field="areaname"
              value-field="areaname"
              :options="areas"
            />
          </n-form-item>
          <n-form-item label="工单类型1:" label-placement="left" style="width: 200px">
            <n-select v-model:value="selectedPanelTypes" multiple clearable :options="panelTypes" />
          </n-form-item>
          <n-form-item label="" label-placement="left">
            <n-button type="primary" :on-click="getFpyData">
              <template #icon><icon-mdi-map-search-outline /></template>
              查询
            </n-button>
          </n-form-item>
        </n-form>
      </n-card>
      <n-card class="rounded-4px shadow-sm">
        <div ref="lineRef" class="w-full h-320px"></div>
      </n-card>
    </n-space>
    <n-card class="rounded-4px shadow-sm">
      <vxe-grid v-bind="fpyOptions"></vxe-grid>
    </n-card>
    <n-modal v-model:show="showModal">
      <n-card style="width: 1200px" :bordered="false" size="huge" role="dialog" aria-modal="true">
        <vxe-grid v-bind="lotGridOptions"></vxe-grid>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup lang="tsx">
import { onMounted, reactive, ref } from 'vue';
import type { SelectOption } from 'naive-ui';
import dayjs from 'dayjs';
import type { LineSeriesOption } from 'echarts/charts';
import type { VxeGridProps } from 'vxe-table';
import type { ECOption } from '@/composables/echarts';
import { useEcharts } from '@/composables/echarts';
import { fetchAreaList, fetchFpyData, fetchFpyLotList, fetchFpyLotListByChart, fetchPanelType } from '@/service/api';

const range = ref<[number, number]>([dayjs().startOf('month').valueOf(), Date.now()]);

const areas = ref<Factory.Area[]>([]);
const selectedAreas = ref([]);
// const modelTypes = ref([]);
const selectedModelType = ref('');
const panelTypes = ref<Array<SelectOption>>([]);
const getPanelType = async () => {
  const result = await fetchPanelType();
  if (result.data) {
    const productSpecList: Array<SelectOption> = [];
    result.data.forEach(element => {
      const temp: SelectOption = {
        label: element.enumvalue,
        value: element.enumvalue
      };
      productSpecList.push(temp);
    });
    panelTypes.value = productSpecList;
  }
};
const selectedPanelTypes = ref([]);

const steps = [
  'R01',
  'R02',
  'R03',
  'R04',
  'R05',
  'R06',
  'R07',
  'R08',
  'R09',
  'R10',
  'R11',
  'R12',
  'R13',
  'R14',
  'R16',
  'R19',
  'R25',
  'R35',
  'R38',
  'R39',
  'R51',
  'R52',
  'R53',
  'R54'
];
const showModal = ref(false);

const myOption = ref<ECOption>({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: []
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [],
  yAxis: [],
  series: []
});
const { domRef: lineRef } = useEcharts(myOption as any, domRef => {
  domRef.on('click', parm => {
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    getFpyLotListByChart(parm.name, parm.seriesName);
  });
});

/* const buildChartSelect = (data: Array<QualityReport.FpyData>) => {
  const chartModels: string[] = [];
  modelTypes.value = [];
  data.forEach(element => {
    if (!chartModels.includes(element.modeltype)) {
      chartModels.push(element.modeltype);
      modelTypes.value.push({ label: element.modeltype, value: element.modeltype });
    }
  });
  if (modelTypes.value.length > 0) {
    selectedModelType.value = modelTypes.value[0].value;
  }
};
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const buildChart = (data: any[]) => {
  const legendData: string[] = [];
  const xAxisData: string[] = [];

  data.forEach(element => {
    if (selectedAreas.value.length === 0) {
      // donothing
    } else if (selectedAreas.value.includes(element.AREA) && !legendData.includes(element.AREA)) {
      legendData.push(element.AREA);
    }
    if (!xAxisData.includes(element.DATETIME)) {
      xAxisData.push(element.DATETIME);
    }
  });

  const seriesList: LineSeriesOption[] = [];

  if (legendData.length === 0) {
    const seriesItem: LineSeriesOption = {
      type: 'line',
      smooth: 0.6,
      data: [0]
    };
    const seriesData = [];
    for (let j = 0; j < xAxisData.length; j += 1) {
      const target = data.filter(item => {
        return item.DATETIME === xAxisData[j];
      });
      if (target.length > 0) {
        seriesData.push(target[0].FPY);
      } else {
        seriesData.push(0);
      }
    }
    seriesItem.data = seriesData as number[];
    seriesList.push(seriesItem);
    myOption.value = {
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      tooltip: {
        show: true, // 是否显示提示框组件
        trigger: 'item',
        axisPointer: {
          type: 'none', // 指示器类型，属性值：line直线/shadow阴影/none/cross十字准星
          axis: 'auto', // 指示器坐标轴，属性值：x/y/radius/angle
          snap: true
        }
      },
      xAxis: {
        data: xAxisData
      },
      yAxis: {},
      series: seriesList as any
    };
  } else {
    for (let i = 0; i < legendData.length; i += 1) {
      const seriesItem: LineSeriesOption = {
        name: legendData[i],
        type: 'line',
        smooth: 0.6,
        data: [0]
      };
      const seriesData = [];
      for (let j = 0; j < xAxisData.length; j += 1) {
        const target = data.filter(item => {
          return item.DATETIME === xAxisData[j] && item.AREA === legendData[i];
        });
        if (target.length > 0) {
          seriesData.push(target[0].FPY);
        } else {
          seriesData.push(0);
        }
      }
      seriesItem.data = seriesData as number[];
      seriesList.push(seriesItem);
    }
    myOption.value = {
      tooltip: {
        show: true, // 是否显示提示框组件
        trigger: 'item',
        axisPointer: {
          type: 'none', // 指示器类型，属性值：line直线/shadow阴影/none/cross十字准星
          axis: 'auto', // 指示器坐标轴，属性值：x/y/radius/angle
          snap: true
        }
      },
      legend: {
        data: legendData
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        data: xAxisData
      },
      yAxis: {},
      series: seriesList as any
    };
  }
};

const lotGridOptions = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  showFooter: true,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'EVENTTIME',
      title: '时间',
      width: 160
    },
    {
      field: 'AREANAME',
      title: '车间',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'OLDPROCESSOPERATIONNAME',
      title: '工序',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PRODUCTSPECNAME',
      title: '产品料号',
      width: 160,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'LOTNAME',
      title: '工单号',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'EVENTUSER',
      title: '操作员'
    },
    {
      field: 'INPUT',
      title: '投入'
    },
    {
      field: 'OUTPUT',
      title: '产出'
    },
    {
      field: 'YIELD',
      title: '良率'
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  mergeCells: [],
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

// eslint-disable-next-line max-params
const getFpyLotList = async (dateTime: string, area: string, modelType: string, operation: string) => {
  const result = await fetchFpyLotList(
    dayjs(range.value[0]).format('YYYYMMDDHHmmss'),
    dayjs(range.value[1]).format('YYYYMMDDHHmmss'),
    dateTime,
    area,
    modelType,
    operation
  );
  if (result.data) {
    lotGridOptions.data = result.data;
  }
};

const getFpyLotListByChart = async (dateTime: string, area: string) => {
  showModal.value = true;
  let realarea = area;
  if (selectedAreas.value.length === 0) {
    realarea = '';
  }
  const result = await fetchFpyLotListByChart(
    dayjs(range.value[0]).format('YYYYMMDDHHmmss'),
    dayjs(range.value[1]).format('YYYYMMDDHHmmss'),
    dateTime,
    realarea,
    selectedModelType.value
  );
  if (result.data) {
    lotGridOptions.data = result.data;
  }
};

const showDetailEvent = (row: any, opreation: string) => {
  showModal.value = true;
  let area = row.OLDAREANAME;
  if (area === undefined) {
    area = '';
  }
  let modelType = row.MODELTYPE;
  if (modelType === undefined) {
    modelType = '';
  }
  getFpyLotList(row.DATETIME, area, modelType, opreation);
};

const fpyOptions = reactive<VxeGridProps>({
  border: true,
  height: 300,
  size: 'mini',
  showFooter: true,
  align: null,
  showOverflow: true,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'DATETIME',
      title: '日期',
      width: 80,
      fixed: 'left',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'AREA',
      title: '车间',
      width: 80,
      fixed: 'left',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MODELTYPE',
      title: '型号',
      width: 80,
      fixed: 'left',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      title: '工序名称/工序良率',
      children: [
        {
          field: 'R01',
          title: '上片良率',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R01 !== '0' && row.R01 !== 0 ? (
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R01')}>
                    {row.R01}
                  </span>
                ) : (
                  row.R01
                )
              ];
            }
          }
        },
        {
          field: 'R02',
          title: '清洗',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R02 !== '0' && row.R02 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R02')}>
                    {row.R02}
                  </span>
                ) : (
                  row.R02
                )
              ];
            }
          }
        },
        {
          field: 'R03',
          title: '镀膜',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R03 !== '0' && row.R03 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R03')}>
                    {row.R03}
                  </span>
                ) : (
                  row.R03
                )
              ];
            }
          }
        },
        {
          field: 'R04',
          title: '点胶',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R04 !== '0' && row.R04 !== 0 ? (
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R04')}>
                    {row.R04}
                  </span>
                ) : (
                  row.R04
                )
              ];
            }
          }
        },
        {
          field: 'R05',
          title: '烤胶',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R05 !== '0' && row.R05 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R05')}>
                    {row.R05}
                  </span>
                ) : (
                  row.R05
                )
              ];
            }
          }
        },
        {
          field: 'R09',
          title: '点胶全检',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R09 !== '0' && row.R09 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R09')}>
                    {row.R09}
                  </span>
                ) : (
                  row.R09
                )
              ];
            }
          }
        },
        {
          field: 'R06',
          title: '退火',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R06 !== '0' && row.R06 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R06')}>
                    {row.R06}
                  </span>
                ) : (
                  row.R06
                )
              ];
            }
          }
        },
        {
          field: 'R07',
          title: '微调',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R07 !== '0' && row.R07 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R07')}>
                    {row.R07}
                  </span>
                ) : (
                  row.R07
                )
              ];
            }
          }
        },
        {
          field: 'R08',
          title: '封焊',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R08 !== '0' && row.R08 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R08')}>
                    {row.R08}
                  </span>
                ) : (
                  row.R08
                )
              ];
            }
          }
        },

        {
          field: 'R10',
          title: '细漏',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R10 !== '0' && row.R10 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R10')}>
                    {row.R10}
                  </span>
                ) : (
                  row.R10
                )
              ];
            }
          }
        },
        {
          field: 'R11',
          title: '老化1',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R11 !== '0' && row.R11 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R11')}>
                    {row.R11}
                  </span>
                ) : (
                  row.R11
                )
              ];
            }
          }
        },
        {
          field: 'R12',
          title: '老化2',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R12 !== '0' && row.R12 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R12')}>
                    {row.R12}
                  </span>
                ) : (
                  row.R12
                )
              ];
            }
          }
        },
        {
          field: 'R13',
          title: '回流焊',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R13 !== '0' && row.R13 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R13')}>
                    {row.R13}
                  </span>
                ) : (
                  row.R13
                )
              ];
            }
          }
        },
        {
          field: 'R14',
          title: '测试1',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R14 !== '0' && row.R14 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R14')}>
                    {row.R14}
                  </span>
                ) : (
                  row.R14
                )
              ];
            }
          }
        },
        {
          field: 'R16',
          title: '气密性检测',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R16 !== '0' && row.R16 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R16')}>
                    {row.R16}
                  </span>
                ) : (
                  row.R16
                )
              ];
            }
          }
        },
        {
          field: 'R19',
          title: '回流焊2',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R19 !== '0' && row.R19 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R19')}>
                    {row.R19}
                  </span>
                ) : (
                  row.R19
                )
              ];
            }
          }
        },
        {
          field: 'R25',
          title: '折取',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R25 !== '0' && row.R25 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R25')}>
                    {row.R25}
                  </span>
                ) : (
                  row.R25
                )
              ];
            }
          }
        },
        {
          field: 'R35',
          title: '写入',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R35 !== '0' && row.R35 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R35')}>
                    {row.R35}
                  </span>
                ) : (
                  row.R35
                )
              ];
            }
          }
        },
        {
          field: 'R38',
          title: '烘烤',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R38 !== '0' && row.R38 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R38')}>
                    {row.R38}
                  </span>
                ) : (
                  row.R38
                )
              ];
            }
          }
        },
        {
          field: 'R39',
          title: '温循',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R39 !== '0' && row.R39 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R39')}>
                    {row.R39}
                  </span>
                ) : (
                  row.R39
                )
              ];
            }
          }
        },
        {
          field: 'R51',
          title: '固晶',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R51 !== '0' && row.R51 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R51')}>
                    {row.R51}
                  </span>
                ) : (
                  row.R51
                )
              ];
            }
          }
        },
        {
          field: 'R52',
          title: '打线',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R52 !== '0' && row.R52 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R52')}>
                    {row.R52}
                  </span>
                ) : (
                  row.R52
                )
              ];
            }
          }
        },
        {
          field: 'R53',
          title: '打标签',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R53 !== '0' && row.R53 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R53')}>
                    {row.R53}
                  </span>
                ) : (
                  row.R53
                )
              ];
            }
          }
        },
        {
          field: 'R54',
          title: '出库',
          width: 80,
          slots: {
            // 使用 JSX 渲染
            default: ({ row }) => {
              return [
                row.R54 !== '0' && row.R54 !== 0 ? (
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  <span style="color: blue" onClick={() => showDetailEvent(row, 'R54')}>
                    {row.R54}
                  </span>
                ) : (
                  row.R54
                )
              ];
            }
          }
        }
      ]
    },
    {
      field: 'FPY',
      title: '直通率',
      width: 80,
      fixed: 'right'
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  mergeCells: [],
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const getFpyData = async () => {
  const result = await fetchFpyData(
    dayjs(range.value[0]).format('YYYYMMDDHHmmss'),
    dayjs(range.value[1]).format('YYYYMMDDHHmmss'),
    selectedAreas.value.join(','),
    selectedModelType.value,
    selectedPanelTypes.value.join(',')
  );
  if (result.data) {
    const rawData = result.data;
    rawData.forEach(element => {
      let fpy = 1;
      for (let i = 0; i < steps.length; i += 1) {
        if (element[steps[i]] !== 0) {
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          fpy *= element[steps[i]];
        }
      }
      // eslint-disable-next-line no-param-reassign
      element.FPY = fpy.toFixed(2);
    });
    fpyOptions.data = rawData;
    // buildChartSelect(rawData);
    buildChart(fpyOptions.data);
  }
};

const getAreaList = async () => {
  const result = await fetchAreaList();
  if (result.data) {
    areas.value = result.data;
  }
};

onMounted(async () => {
  getAreaList();
  getPanelType();
});
</script>
<style scoped></style>
